<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pandas数据分析可视化平台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background-color: #f8f9fa;
            padding-top: 20px;
        }
        .container {
            max-width: 1200px;
        }
        .card {
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            border: none;
        }
        .card-header {
            background-color: #0d6efd;
            color: white;
            font-weight: bold;
        }
        .btn-primary {
            background-color: #0d6efd;
            border-color: #0d6efd;
        }
        .btn-primary:hover {
            background-color: #0b5ed7;
            border-color: #0a58ca;
        }
        .feature-icon {
            font-size: 2rem;
            color: #0d6efd;
            margin-bottom: 10px;
        }
        .jumbotron {
            background-color: #e9ecef;
            padding: 2rem;
            border-radius: 0.3rem;
            margin-bottom: 2rem;
        }
        .viz-container {
            text-align: center;
            margin-top: 20px;
            padding: 20px;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="jumbotron text-center">
            <h1>Pandas数据分析可视化平台</h1>
            <p class="lead">基于FastAPI和Pandas的数据处理与可视化平台，支持CSV和Excel文件</p>
        </div>
        
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        上传文件
                    </div>
                    <div class="card-body">
                        <form id="upload-form">
                            <div class="mb-3">
                                <label for="file" class="form-label">选择CSV或Excel文件</label>
                                <input type="file" class="form-control" id="file" name="file" accept=".csv,.xlsx,.xls">
                            </div>
                            <button type="submit" class="btn btn-primary">上传文件</button>
                        </form>
                        <div class="mt-3" id="upload-result"></div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        数据分析
                    </div>
                    <div class="card-body" id="analysis-card">
                        <div id="file-info">
                            <p>请先上传文件以查看数据信息</p>
                        </div>
                        <div class="mt-3" id="analysis-options" style="display: none;">
                            <h5>选择分析类型:</h5>
                            <div class="list-group">
                                <a href="#" class="list-group-item list-group-item-action" id="basic-info">基本数据信息</a>
                                <a href="#" class="list-group-item list-group-item-action" id="full-report">完整分析报告</a>
                                <a href="#" class="list-group-item list-group-item-action" id="data-preview">数据预览</a>
                                <a href="#" class="list-group-item list-group-item-action" id="df-variables">DataFrame变量和函数</a>
                                <a href="#" class="list-group-item list-group-item-action" id="create-viz">创建可视化图表</a>
                                <a href="#" class="list-group-item list-group-item-action" id="show-filter">数据筛选</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 数据筛选卡片 -->
        <div class="card mt-4" id="filter-options" style="display: none;">
            <div class="card-header">
                数据筛选
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <h5>当前筛选条件</h5>
                    <div id="filter-conditions-list" class="mb-3">
                        <div class="alert alert-info">尚未添加筛选条件</div>
                    </div>
                    <button type="button" class="btn btn-primary mb-3" id="add-filter-condition">添加筛选条件</button>
                    <button type="button" class="btn btn-success mb-3 ms-2" id="apply-filters" style="display: none;">应用筛选</button>
                    <button type="button" class="btn btn-secondary mb-3 ms-2" id="save-filtered-data" style="display: none;">保存筛选结果</button>
                    <button type="button" class="btn btn-warning mb-3 ms-2" id="export-filtered-data" style="display: none;">导出筛选结果 <i class="bi bi-download"></i></button>
                    <button type="button" class="btn btn-danger mb-3 ms-2" id="clear-filters" style="display: none;">清除全部筛选</button>
                </div>
                
                <!-- 添加筛选条件的模态框 -->
                <div class="modal fade" id="filter-modal" tabindex="-1" aria-labelledby="filter-modal-label" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="filter-modal-label">添加筛选条件</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <form id="filter-form">
                                    <div class="mb-3">
                                        <label for="filter-column" class="form-label">选择列</label>
                                        <select class="form-select" id="filter-column">
                                            <!-- 动态填充 -->
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="filter-operator" class="form-label">操作符</label>
                                        <select class="form-select" id="filter-operator">
                                            <option value="eq">等于 (=)</option>
                                            <option value="gt">大于 (>)</option>
                                            <option value="lt">小于 (<)</option>
                                            <option value="ge">大于等于 (>=)</option>
                                            <option value="le">小于等于 (<=)</option>
                                            <option value="contains">包含</option>
                                            <option value="between">介于两值之间</option>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="filter-value" class="form-label">值</label>
                                        <input type="text" class="form-control" id="filter-value" placeholder="输入筛选值">
                                    </div>
                                    
                                    <div class="mb-3" id="filter-value2-container" style="display: none;">
                                        <label for="filter-value2" class="form-label">值 (上限)</label>
                                        <input type="text" class="form-control" id="filter-value2" placeholder="输入上限值">
                                    </div>
                                    
                                    <div class="mb-3" id="filter-column-info">
                                        <!-- 列信息将在这里显示 -->
                                    </div>
                                </form>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary" id="confirm-add-filter">添加</button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 筛选结果区域 -->
                <div id="filter-results" class="mt-4" style="display: none;">
                    <h5>筛选结果</h5>
                    <div id="filter-results-content">
                        <!-- 筛选结果将在这里显示 -->
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 可视化设置 -->
        <div class="card mt-4" id="viz-options" style="display: none;">
            <div class="card-header">
                创建可视化图表
            </div>
            <div class="card-body">
                <form id="viz-form">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="mb-3">
                                <label for="plot-type" class="form-label">图表类型</label>
                                <select class="form-select" id="plot-type">
                                    <option value="bar">柱状图</option>
                                    <option value="line">折线图</option>
                                    <option value="pie">饼图</option>
                                    <option value="scatter">散点图</option>
                                    <option value="heatmap">相关性热力图</option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="x-column" class="form-label">X轴列</label>
                                <select class="form-select" id="x-column">
                                    <!-- 动态填充 -->
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="y-column" class="form-label">Y轴列</label>
                                <select class="form-select" id="y-column">
                                    <!-- 动态填充 -->
                                </select>
                            </div>
                            
                            <div class="mb-3" id="y-label-container" style="display: none;">
                                <label for="y-label" class="form-label">Y轴标签</label>
                                <input type="text" class="form-control" id="y-label" placeholder="默认为'数量'">
                                <small class="form-text text-muted">柱状图的Y轴标签，留空则默认显示"数量"</small>
                            </div>
                            
                            <div class="mb-3">
                                <label for="chart-title" class="form-label">图表标题</label>
                                <input type="text" class="form-control" id="chart-title" placeholder="输入图表标题">
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">生成图表</button>
                </form>
            </div>
        </div>
        
        <!-- 数据展示区域 -->
        <div class="card mt-4" id="results-card" style="display: none;">
            <div class="card-header">
                分析结果
            </div>
            <div class="card-body" id="results-container">
                <!-- 结果将在这里显示 -->
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let currentFilePath = '';
        let fileColumns = [];
        
        // 文件上传处理
        document.getElementById('upload-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData();
            const fileInput = document.getElementById('file');
            
            if (fileInput.files.length === 0) {
                alert('请选择文件');
                return;
            }
            
            formData.append('file', fileInput.files[0]);
            
            try {
                const response = await fetch('/module/upload-file', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    document.getElementById('upload-result').innerHTML = 
                        `<div class="alert alert-success">文件 "${result.filename}" 上传成功</div>`;
                    
                    // 保存文件路径和列信息
                    currentFilePath = result.saved_location;
                    fileColumns = result.columns;
                    
                    // 显示分析选项
                    document.getElementById('analysis-options').style.display = 'block';
                    document.getElementById('file-info').innerHTML = 
                        `<p>当前文件: ${result.filename}</p>
                        <p>数据维度: ${result.shape[0]} 行 x ${result.shape[1]} 列</p>`;
                    
                    // 更新可视化选项中的列选择器
                    populateColumnSelectors(fileColumns);
                } else {
                    document.getElementById('upload-result').innerHTML = 
                        `<div class="alert alert-danger">上传失败: ${result.detail}</div>`;
                }
            } catch (error) {
                console.error('上传错误:', error);
                document.getElementById('upload-result').innerHTML = 
                    `<div class="alert alert-danger">上传出错: ${error.message}</div>`;
            }
        });
        
        // 填充列选择器
        function populateColumnSelectors(columns) {
            const xSelector = document.getElementById('x-column');
            const ySelector = document.getElementById('y-column');
            
            // 清空现有选项
            xSelector.innerHTML = '';
            ySelector.innerHTML = '';
            
            // 添加新选项
            columns.forEach(column => {
                xSelector.innerHTML += `<option value="${column}">${column}</option>`;
                ySelector.innerHTML += `<option value="${column}">${column}</option>`;
            });
        }
        
        // 基本信息按钮点击处理
        document.getElementById('basic-info').addEventListener('click', async function(e) {
            e.preventDefault();
            
            if (!currentFilePath) {
                alert('请先上传文件');
                return;
            }
            
            try {
                const response = await fetch(`/module/file-info/${encodeURIComponent(currentFilePath)}`);
                const result = await response.json();
                
                if (response.ok) {
                    // 显示结果区域
                    document.getElementById('results-card').style.display = 'block';
                    
                    // 格式化并显示结果
                    let html = '<h4>基本数据信息</h4>';
                    html += `<p>数据维度: ${result.shape[0]} 行 x ${result.shape[1]} 列</p>`;
                    html += '<h5>列信息:</h5><ul>';
                    
                    result.columns.forEach(column => {
                        const dataType = result.dtypes[column];
                        const hasNull = result.has_null[column] ? '有缺失值' : '无缺失值';
                        html += `<li>${column} (${dataType}) - ${hasNull}</li>`;
                    });
                    
                    html += '</ul>';
                    
                    // 如果有数值描述信息
                    if (result.describe) {
                        html += '<h5>数值统计描述:</h5>';
                        html += '<div class="table-responsive"><table class="table table-striped">';
                        html += '<thead><tr><th>统计量</th>';
                        
                        // 表头
                        for (const column in result.describe) {
                            html += `<th>${column}</th>`;
                        }
                        html += '</tr></thead><tbody>';
                        
                        // 统计值行
                        const stats = ['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max'];
                        stats.forEach(stat => {
                            html += `<tr><td><strong>${stat}</strong></td>`;
                            for (const column in result.describe) {
                                if (result.describe[column][stat] !== undefined) {
                                    const value = parseFloat(result.describe[column][stat]).toFixed(2);
                                    html += `<td>${value}</td>`;
                                } else {
                                    html += '<td>-</td>';
                                }
                            }
                            html += '</tr>';
                        });
                        
                        html += '</tbody></table></div>';
                    }
                    
                    document.getElementById('results-container').innerHTML = html;
                } else {
                    document.getElementById('results-container').innerHTML = 
                        `<div class="alert alert-danger">获取数据信息失败: ${result.detail}</div>`;
                }
            } catch (error) {
                console.error('获取数据信息错误:', error);
                document.getElementById('results-container').innerHTML = 
                    `<div class="alert alert-danger">获取数据信息出错: ${error.message}</div>`;
            }
        });
        
        // 完整报告按钮点击处理
        document.getElementById('full-report').addEventListener('click', async function(e) {
            e.preventDefault();
            
            if (!currentFilePath) {
                alert('请先上传文件');
                return;
            }
            
            try {
                // 显示结果区域并设置加载消息
                document.getElementById('results-card').style.display = 'block';
                document.getElementById('results-container').innerHTML = 
                    '<div class="alert alert-info">正在生成报告，请稍候...</div>';
                
                // 获取报告
                const response = await fetch(`/module/analyze-csv/${encodeURIComponent(currentFilePath)}`);
                
                if (response.ok) {
                    const html = await response.text();
                    
                    // 创建iframe以显示完整HTML响应
                    const iframe = document.createElement('iframe');
                    iframe.style.width = '100%';
                    iframe.style.height = '600px';
                    iframe.style.border = 'none';
                    
                    document.getElementById('results-container').innerHTML = '';
                    document.getElementById('results-container').appendChild(iframe);
                    
                    // 写入HTML内容
                    iframe.contentWindow.document.open();
                    iframe.contentWindow.document.write(html);
                    iframe.contentWindow.document.close();
                } else {
                    const errorText = await response.text();
                    document.getElementById('results-container').innerHTML = 
                        `<div class="alert alert-danger">获取报告失败: ${errorText}</div>`;
                }
            } catch (error) {
                console.error('获取报告错误:', error);
                document.getElementById('results-container').innerHTML = 
                    `<div class="alert alert-danger">获取报告出错: ${error.message}</div>`;
            }
        });
        
        // 数据预览按钮点击处理
        document.getElementById('data-preview').addEventListener('click', async function(e) {
            e.preventDefault();
            
            if (!currentFilePath) {
                alert('请先上传文件');
                return;
            }
            
            try {
                // 显示结果区域并设置加载消息
                document.getElementById('results-card').style.display = 'block';
                document.getElementById('results-container').innerHTML = 
                    '<div class="alert alert-info">正在加载数据预览，请稍候...</div>';
                
                // 获取数据预览
                const response = await fetch(`/module/data-preview/${encodeURIComponent(currentFilePath)}`);
                
                if (response.ok) {
                    const result = await response.json();
                    
                    // 创建HTML内容
                    let html = '<h4>数据预览</h4>';
                    
                    // 显示基本信息
                    html += `<div class="alert alert-light">
                        <p>总行数: ${result.rows}</p>
                        <p>总列数: ${result.columns.length}</p>
                    </div>`;
                    
                    // 显示数据类型信息
                    html += '<div class="card mb-4"><div class="card-header">数据类型信息</div><div class="card-body">';
                    html += `<pre>${result.info}</pre>`;
                    html += '</div></div>';
                    
                    // 显示列统计信息
                    html += '<div class="card mb-4"><div class="card-header">列统计信息</div><div class="card-body">';
                    html += '<div class="table-responsive"><table class="table table-striped table-sm">';
                    html += '<thead><tr><th>列名</th><th>数据类型</th><th>唯一值数量</th><th>空值数量</th></tr></thead><tbody>';
                    
                    result.columns.forEach(col => {
                        html += `<tr>
                            <td>${col}</td>
                            <td>${result.dtypes[col]}</td>
                            <td>${result.unique_counts[col]}</td>
                            <td>${result.null_counts[col]}</td>
                        </tr>`;
                    });
                    
                    html += '</tbody></table></div>';
                    html += '</div></div>';
                    
                    // 显示前5行数据
                    html += '<div class="card"><div class="card-header">前5行数据</div><div class="card-body">';
                    html += '<div class="table-responsive"><table class="table table-striped table-sm">';
                    
                    // 表头
                    html += '<thead><tr>';
                    result.columns.forEach(col => {
                        html += `<th>${col}</th>`;
                    });
                    html += '</tr></thead><tbody>';
                    
                    // 表格数据
                    result.head.forEach(row => {
                        html += '<tr>';
                        result.columns.forEach(col => {
                            html += `<td>${row[col] !== null ? row[col] : 'N/A'}</td>`;
                        });
                        html += '</tr>';
                    });
                    
                    html += '</tbody></table></div>';
                    html += '</div></div>';
                    
                    // 添加描述统计信息
                    if (result.describe) {
                        html += '<div class="card mt-4"><div class="card-header">描述统计信息 (df.describe())</div><div class="card-body">';
                        html += '<div class="table-responsive"><table class="table table-striped table-sm">';
                        
                        // 表头
                        html += '<thead><tr><th>统计量</th>';
                        Object.keys(result.describe).forEach(col => {
                            html += `<th>${col}</th>`;
                        });
                        html += '</tr></thead><tbody>';
                        
                        // 统计值行
                        const stats = ['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max'];
                        stats.forEach(stat => {
                            html += `<tr><td><strong>${stat}</strong>`;
                            
                            // 添加函数含义说明的提示工具
                            if (result.describe_functions && result.describe_functions[stat]) {
                                html += `<span class="ms-1" data-bs-toggle="tooltip" title="${result.describe_functions[stat]}">
                                            <i class="fas fa-info-circle text-info"></i>
                                         </span>`;
                            }
                            
                            html += `</td>`;
                            
                            Object.keys(result.describe).forEach(col => {
                                if (result.describe[col][stat] !== undefined && result.describe[col][stat] !== null) {
                                    const value = parseFloat(result.describe[col][stat]).toFixed(2);
                                    html += `<td>${value}</td>`;
                                } else {
                                    html += '<td>-</td>';
                                }
                            });
                            html += '</tr>';
                        });
                        
                        html += '</tbody></table></div>';
                        
                        // 添加统计函数含义说明
                        if (result.describe_functions) {
                            html += '<div class="mt-3"><h6>统计函数含义说明：</h6><ul class="list-group">';
                            for (const [stat, desc] of Object.entries(result.describe_functions)) {
                                html += `<li class="list-group-item d-flex justify-content-between align-items-center">
                                            <strong>${stat}</strong>
                                            <span>${desc}</span>
                                         </li>`;
                            }
                            html += '</ul></div>';
                        }
                        
                        html += '</div></div>';
                    }
                    
                    document.getElementById('results-container').innerHTML = html;
                    
                    // 初始化工具提示
                    document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(tooltip => {
                        new bootstrap.Tooltip(tooltip);
                    });
                } else {
                    let errorMessage = '加载数据预览失败';
                    try {
                        const errorData = await response.json();
                        errorMessage = errorData.detail || '未知错误';
                    } catch (e) {
                        // 如果响应不是JSON格式
                        errorMessage = await response.text();
                    }
                    document.getElementById('results-container').innerHTML = 
                        `<div class="alert alert-danger">加载数据预览失败: ${errorMessage}</div>`;
                }
            } catch (error) {
                console.error('加载数据预览错误:', error);
                document.getElementById('results-container').innerHTML = 
                    `<div class="alert alert-danger">加载数据预览出错: ${error.message}</div>`;
            }
        });
        
        // DataFrame变量和函数预览
        document.getElementById('df-variables').addEventListener('click', async function(e) {
            e.preventDefault();
            
            if (!currentFilePath) {
                alert('请先上传文件');
                return;
            }
            
            try {
                // 显示结果区域并设置加载消息
                document.getElementById('results-card').style.display = 'block';
                document.getElementById('results-container').innerHTML = 
                    '<div class="alert alert-info">正在加载DataFrame变量和函数信息，请稍候...</div>';
                
                // 获取DataFrame信息
                const response = await fetch(`/module/dataframe-info/${encodeURIComponent(currentFilePath)}`);
                
                if (response.ok) {
                    const result = await response.json();
                    
                    // 创建HTML内容
                    let html = '<h4>DataFrame详细信息</h4>';
                    
                    // 显示基本信息
                    html += `<div class="alert alert-light">
                        <p><strong>形状</strong>: ${result.basic_info.shape[0]} 行 × ${result.basic_info.shape[1]} 列</p>
                        <p><strong>总元素数</strong>: ${result.basic_info.size}</p>
                        <p><strong>维度</strong>: ${result.basic_info.ndim}</p>
                        <p><strong>内存占用</strong>: ${result.basic_info.memory_usage_human}</p>
                    </div>`;
                    
                    // 创建导航标签
                    html += `
                    <ul class="nav nav-tabs mb-3" id="dfInfoTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="columns-tab" data-bs-toggle="tab" data-bs-target="#columns" type="button" role="tab">列统计信息</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="methods-tab" data-bs-toggle="tab" data-bs-target="#methods" type="button" role="tab">方法和属性</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="describe-tab" data-bs-toggle="tab" data-bs-target="#describe" type="button" role="tab">描述统计</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="correlation-tab" data-bs-toggle="tab" data-bs-target="#correlation" type="button" role="tab">相关性</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="headtail-tab" data-bs-toggle="tab" data-bs-target="#headtail" type="button" role="tab">头尾数据</button>
                        </li>
                    </ul>
                    <div class="tab-content" id="dfInfoTabsContent">`;
                    
                    // 列统计信息标签内容
                    html += `<div class="tab-pane fade show active" id="columns" role="tabpanel">
                        <div class="accordion" id="columnsAccordion">`;
                    
                    // 为每列创建可折叠的卡片
                    Object.keys(result.column_stats).forEach((col, index) => {
                        const colStats = result.column_stats[col];
                        const colId = `column-${index}`;
                        
                        html += `
                        <div class="accordion-item">
                            <h2 class="accordion-header" id="heading-${colId}">
                                <button class="accordion-button ${index > 0 ? 'collapsed' : ''}" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-${colId}">
                                    ${col} (${colStats.type})
                                </button>
                            </h2>
                            <div id="collapse-${colId}" class="accordion-collapse collapse ${index === 0 ? 'show' : ''}" data-bs-parent="#columnsAccordion">
                                <div class="accordion-body">
                                    <ul class="list-group">
                                        <li class="list-group-item d-flex justify-content-between align-items-center">
                                            数据类型 <span class="badge bg-primary rounded-pill">${colStats.type}</span>
                                        </li>
                                        <li class="list-group-item d-flex justify-content-between align-items-center">
                                            空值数量 <span class="badge bg-primary rounded-pill">${colStats.null_count}</span>
                                        </li>
                                        <li class="list-group-item d-flex justify-content-between align-items-center">
                                            唯一值数量 <span class="badge bg-primary rounded-pill">${colStats.unique_count}</span>
                                        </li>`;
                        
                        // 针对不同类型的列显示特定信息
                        if (colStats.min !== undefined) {
                            html += `
                                        <li class="list-group-item d-flex justify-content-between align-items-center">
                                            最小值 <span class="badge bg-secondary rounded-pill">${colStats.min}</span>
                                        </li>
                                        <li class="list-group-item d-flex justify-content-between align-items-center">
                                            最大值 <span class="badge bg-secondary rounded-pill">${colStats.max}</span>
                                        </li>
                                        <li class="list-group-item d-flex justify-content-between align-items-center">
                                            平均值 <span class="badge bg-secondary rounded-pill">${colStats.mean}</span>
                                        </li>
                                        <li class="list-group-item d-flex justify-content-between align-items-center">
                                            中位数 <span class="badge bg-secondary rounded-pill">${colStats.median}</span>
                                        </li>
                                        <li class="list-group-item d-flex justify-content-between align-items-center">
                                            标准差 <span class="badge bg-secondary rounded-pill">${colStats.std}</span>
                                        </li>`;
                        }
                        
                        if (colStats.most_common) {
                            html += `<li class="list-group-item">最常见值:
                                        <ul class="list-group mt-2">`;
                            Object.entries(colStats.most_common).forEach(([value, count]) => {
                                html += `<li class="list-group-item d-flex justify-content-between align-items-center">
                                            ${value} <span class="badge bg-info rounded-pill">${count}</span>
                                        </li>`;
                            });
                            html += `</ul>
                                    </li>`;
                        }
                        
                        if (colStats.mean_length !== undefined) {
                            html += `<li class="list-group-item d-flex justify-content-between align-items-center">
                                        平均字符长度 <span class="badge bg-secondary rounded-pill">${colStats.mean_length !== null ? colStats.mean_length.toFixed(2) : 'N/A'}</span>
                                    </li>`;
                        }
                        
                        if (colStats.min_date) {
                            html += `<li class="list-group-item d-flex justify-content-between align-items-center">
                                        最早日期 <span class="badge bg-secondary rounded-pill">${colStats.min_date}</span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        最晚日期 <span class="badge bg-secondary rounded-pill">${colStats.max_date}</span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        范围(天) <span class="badge bg-secondary rounded-pill">${colStats.range_days}</span>
                                    </li>`;
                        }
                        
                        html += `
                                    </ul>
                                </div>
                            </div>
                        </div>`;
                    });
                    
                    html += `</div></div>`; // 结束列统计标签内容
                    
                    // 方法和属性标签内容
                    html += `<div class="tab-pane fade" id="methods" role="tabpanel">
                        <div class="accordion" id="methodsAccordion">`;
                    
                    // 为每个方法类别创建可折叠的卡片
                    Object.keys(result.methods_by_category).forEach((category, index) => {
                        const methods = result.methods_by_category[category];
                        const categoryId = `category-${index}`;
                        
                        if (methods.length === 0) return;
                        
                        html += `
                        <div class="accordion-item">
                            <h2 class="accordion-header" id="heading-${categoryId}">
                                <button class="accordion-button ${index > 0 ? 'collapsed' : ''}" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-${categoryId}">
                                    ${category} (${methods.length})
                                </button>
                            </h2>
                            <div id="collapse-${categoryId}" class="accordion-collapse collapse ${index === 0 ? 'show' : ''}" data-bs-parent="#methodsAccordion">
                                <div class="accordion-body">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>名称</th>
                                                <th>类型</th>
                                                <th>描述</th>
                                            </tr>
                                        </thead>
                                        <tbody>`;
                        
                        methods.forEach(method => {
                            html += `
                                            <tr>
                                                <td><code>${method.name}</code></td>
                                                <td>${method.is_callable ? '方法' : '属性'}</td>
                                                <td>${method.description}</td>
                                            </tr>`;
                        });
                        
                        html += `
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>`;
                    });
                    
                    html += `</div></div>`; // 结束方法和属性标签内容
                    
                    // 描述统计标签内容
                    html += `<div class="tab-pane fade" id="describe" role="tabpanel">`;
                    
                    if (result.describe) {
                        html += `<div class="table-responsive">
                            <table class="table table-sm table-striped">
                                <thead>
                                    <tr>
                                        <th>统计量</th>`;
                        
                        // 表头 - 列名
                        Object.keys(result.describe).forEach(col => {
                            html += `<th>${col}</th>`;
                        });
                        
                        html += `</tr>
                                </thead>
                                <tbody>`;
                        
                        // 行 - 统计量
                        const stats = ['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max'];
                        stats.forEach(stat => {
                            html += `<tr>
                                <td><strong>${stat}</strong></td>`;
                            
                            Object.keys(result.describe).forEach(col => {
                                const value = result.describe[col][stat];
                                html += `<td>${value !== undefined && value !== null ? (typeof value === 'number' ? value.toFixed(2) : value) : '-'}</td>`;
                            });
                            
                            html += `</tr>`;
                        });
                        
                        html += `</tbody>
                            </table>
                        </div>`;
                    } else {
                        html += `<div class="alert alert-info">无法生成描述统计信息</div>`;
                    }
                    
                    html += `</div>`; // 结束描述统计标签内容
                    
                    // 相关性标签内容
                    html += `<div class="tab-pane fade" id="correlation" role="tabpanel">`;
                    
                    if (result.correlation) {
                        html += `<div class="table-responsive">
                            <table class="table table-sm table-striped">
                                <thead>
                                    <tr>
                                        <th></th>`;
                        
                        // 表头 - 列名
                        Object.keys(result.correlation).forEach(col => {
                            html += `<th>${col}</th>`;
                        });
                        
                        html += `</tr>
                                </thead>
                                <tbody>`;
                        
                        // 行 - 列与其他列的相关性
                        Object.keys(result.correlation).forEach(row => {
                            html += `<tr>
                                <td><strong>${row}</strong></td>`;
                            
                            Object.keys(result.correlation[row]).forEach(col => {
                                const value = result.correlation[row][col];
                                // 根据相关性值设置不同的背景色
                                let cellClass = '';
                                if (value !== null) {
                                    if (value > 0.7) cellClass = 'bg-success text-white';
                                    else if (value < -0.7) cellClass = 'bg-danger text-white';
                                    else if (value > 0.4) cellClass = 'bg-info text-white';
                                    else if (value < -0.4) cellClass = 'bg-warning';
                                }
                                
                                html += `<td class="${cellClass}">${value !== null && value !== undefined ? value.toFixed(2) : '-'}</td>`;
                            });
                            
                            html += `</tr>`;
                        });
                        
                        html += `</tbody>
                            </table>
                        </div>
                        <div class="alert alert-light mt-3">
                            <small>
                                <ul>
                                    <li><strong>绿色</strong>: 强正相关 (> 0.7)</li>
                                    <li><strong>红色</strong>: 强负相关 (< -0.7)</li>
                                    <li><strong>蓝色</strong>: 中等正相关 (0.4 - 0.7)</li>
                                    <li><strong>黄色</strong>: 中等负相关 (-0.4 - -0.7)</li>
                                </ul>
                            </small>
                        </div>`;
                    } else {
                        html += `<div class="alert alert-info">无法生成相关性矩阵，可能没有足够的数值型列</div>`;
                    }
                    
                    html += `</div>`; // 结束相关性标签内容
                    
                    // 头尾数据标签内容
                    html += `<div class="tab-pane fade" id="headtail" role="tabpanel">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">前5行数据</div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-striped table-sm">
                                                <thead>
                                                    <tr>`;
                    
                    // 表头
                    result.head_data[0] && Object.keys(result.head_data[0]).forEach(col => {
                        html += `<th>${col}</th>`;
                    });
                    
                    html += `</tr>
                                                </thead>
                                                <tbody>`;
                    
                    // 头部数据
                    result.head_data.forEach(row => {
                        html += `<tr>`;
                        Object.values(row).forEach(val => {
                            html += `<td>${val !== null ? val : 'N/A'}</td>`;
                        });
                        html += `</tr>`;
                    });
                    
                    html += `</tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">后5行数据</div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-striped table-sm">
                                                <thead>
                                                    <tr>`;
                    
                    // 表头
                    result.tail_data[0] && Object.keys(result.tail_data[0]).forEach(col => {
                        html += `<th>${col}</th>`;
                    });
                    
                    html += `</tr>
                                                </thead>
                                                <tbody>`;
                    
                    // 尾部数据
                    result.tail_data.forEach(row => {
                        html += `<tr>`;
                        Object.values(row).forEach(val => {
                            html += `<td>${val !== null ? val : 'N/A'}</td>`;
                        });
                        html += `</tr>`;
                    });
                    
                    html += `</tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>`; // 结束头尾数据标签内容
                    
                    html += `</div>`; // 结束标签内容容器
                    
                    document.getElementById('results-container').innerHTML = html;
                    
                    // 初始化Bootstrap标签
                    const triggerTabList = [].slice.call(document.querySelectorAll('#dfInfoTabs button'));
                    triggerTabList.forEach(function (triggerEl) {
                        new bootstrap.Tab(triggerEl);
                    });
                    
                } else {
                    let errorMessage = '加载DataFrame信息失败';
                    try {
                        const errorData = await response.json();
                        errorMessage = errorData.detail || '未知错误';
                    } catch (e) {
                        // 如果响应不是JSON格式
                        errorMessage = await response.text();
                    }
                    document.getElementById('results-container').innerHTML = 
                        `<div class="alert alert-danger">加载DataFrame信息失败: ${errorMessage}</div>`;
                }
            } catch (error) {
                console.error('加载DataFrame信息错误:', error);
                document.getElementById('results-container').innerHTML = 
                    `<div class="alert alert-danger">加载DataFrame信息出错: ${error.message}</div>`;
            }
        });
        
        // 创建可视化按钮点击处理
        document.getElementById('create-viz').addEventListener('click', function(e) {
            e.preventDefault();
            
            if (!currentFilePath) {
                alert('请先上传文件');
                return;
            }
            
            // 显示可视化选项卡片
            document.getElementById('viz-options').style.display = 'block';
            
            // 隐藏其他卡片
            document.getElementById('filter-options').style.display = 'none';
            
            // 填充列下拉框
            const xColumnSelect = document.getElementById('x-column');
            const yColumnSelect = document.getElementById('y-column');
            
            xColumnSelect.innerHTML = '';
            yColumnSelect.innerHTML = '';
            
            fileColumns.forEach(column => {
                xColumnSelect.innerHTML += `<option value="${column}">${column}</option>`;
                yColumnSelect.innerHTML += `<option value="${column}">${column}</option>`;
            });
            
            // 清除筛选后可视化的状态
            window.currentFilterConditions = null;
            
            // 移除提示信息（如果存在）
            const existingAlert = document.getElementById('filtered-viz-alert');
            if (existingAlert) {
                existingAlert.remove();
            }
        });
        
        // 可视化表单提交
        document.getElementById('viz-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const plotType = document.getElementById('plot-type').value;
            const xColumn = document.getElementById('x-column').value;
            let yColumn = document.getElementById('y-column').value;
            const title = document.getElementById('chart-title').value;
            let yLabel = null;
            
            // 获取Y轴标签（仅用于柱状图）
            if (plotType === 'bar') {
                yLabel = document.getElementById('y-label').value || "数量";
            }
            
            // 对于热力图，不需要y轴
            if (plotType === 'heatmap') {
                yColumn = null;
            }
            
            // 验证必填字段
            if (!plotType || !xColumn) {
                alert('请填写所有必填字段');
                return;
            }
            
            // 对于非热力图，需要验证y轴列
            if (plotType !== 'heatmap' && !yColumn) {
                alert('请选择Y轴列');
                return;
            }
            
            try {
                // 显示结果卡片
                document.getElementById('results-card').style.display = 'block';
                document.getElementById('results-container').innerHTML = '<div class="alert alert-info">正在生成图表，请稍候...</div>';
                
                // 准备可视化请求参数
                const visualizationParams = {
                    file_path: currentFilePath,
                    plot_type: plotType,
                    x_column: xColumn,
                    y_column: yColumn,
                    title: title || undefined,
                    y_label: yLabel
                };
                
                let response;
                
                // 检查是否是基于筛选结果的可视化
                if (window.currentFilterConditions && window.currentFilterConditions.length > 0) {
                    // 发送基于筛选的可视化请求
                    response = await fetch('/module/visualize-filtered', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            filter_params: {
                                file_path: currentFilePath,
                                conditions: window.currentFilterConditions
                            },
                            visualization_params: visualizationParams
                        })
                    });
                } else {
                    // 发送标准可视化请求
                    response = await fetch('/module/visualize', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(visualizationParams)
                    });
                }
                
                if (response.ok) {
                    const htmlContent = await response.text();
                    document.getElementById('results-container').innerHTML = htmlContent;
                } else {
                    // 尝试解析JSON错误
                    let errorData;
                    try {
                        errorData = await response.json();
                        document.getElementById('results-container').innerHTML = 
                            `<div class="alert alert-danger">生成图表失败: ${errorData.detail || '未知错误'}</div>`;
                    } catch (jsonError) {
                        // 如果不是JSON，则直接显示错误文本
                        const errorText = await response.text();
                        document.getElementById('results-container').innerHTML = 
                            `<div class="alert alert-danger">生成图表失败: ${errorText || '未知错误'}</div>`;
                    }
                }
            } catch (error) {
                console.error('可视化错误:', error);
                document.getElementById('results-container').innerHTML = 
                    `<div class="alert alert-danger">可视化错误: ${error.message}</div>`;
            }
        });
        
        // 监听图表类型变化，显示或隐藏相应的选项
        document.getElementById('plot-type').addEventListener('change', function() {
            const plotType = this.value;
            const yColumnContainer = document.querySelector('.mb-3:nth-child(3)');
            const yLabelContainer = document.getElementById('y-label-container');
            
            // 对于热力图，隐藏Y轴列选择
            if (plotType === 'heatmap') {
                yColumnContainer.style.display = 'none';
            } else {
                yColumnContainer.style.display = 'block';
            }
            
            // 对于柱状图，显示Y轴标签输入框
            if (plotType === 'bar') {
                yLabelContainer.style.display = 'block';
            } else {
                yLabelContainer.style.display = 'none';
            }
            
            // 更新Y轴列的帮助文本
            const yColumnHelpText = document.getElementById('y-column-help') || 
                createHelpText('y-column-help', yColumnContainer);
                
            if (plotType === 'pie') {
                yColumnHelpText.textContent = '选择一个数值列作为饼图的值';
            } else if (plotType === 'bar') {
                yColumnHelpText.textContent = '选择一个数值列作为Y轴值';
            } else if (plotType === 'line') {
                yColumnHelpText.textContent = '选择一个数值列作为Y轴值';
            } else if (plotType === 'scatter') {
                yColumnHelpText.textContent = '散点图的Y轴值，最好是数值型';
            } else if (plotType === 'heatmap') {
                yColumnHelpText.textContent = '相关性热力图会分析所有数值列';
            }
            
            // 同样更新X轴的帮助文本
            const xColumnHelpText = document.getElementById('x-column-help') || 
                createHelpText('x-column-help', document.querySelector('.mb-3:nth-child(2)'));
                
            if (plotType === 'pie') {
                xColumnHelpText.textContent = '选择一个分类列作为饼图的标签';
            } else if (plotType === 'bar') {
                xColumnHelpText.textContent = '选择一个分类列作为X轴标签';
            } else if (plotType === 'line') {
                xColumnHelpText.textContent = '选择一个分类列或日期列作为X轴';
            } else if (plotType === 'scatter') {
                xColumnHelpText.textContent = '散点图的X轴值，最好是数值型';
            } else if (plotType === 'heatmap') {
                xColumnHelpText.textContent = '相关性热力图会分析所有数值列';
            }
        });
        
        // 创建帮助文本元素
        function createHelpText(id, parentElement) {
            const helpText = document.createElement('small');
            helpText.id = id;
            helpText.className = 'form-text text-muted';
            parentElement.appendChild(helpText);
            return helpText;
        }
        
        // ===== 数据筛选功能 =====
        // 全局变量存储筛选条件
        let filterConditions = [];
        let filteredFilePath = '';
        
        // 显示筛选界面的事件处理器
        document.getElementById('show-filter').addEventListener('click', function(e) {
            e.preventDefault();
            
            if (!currentFilePath) {
                alert('请先上传文件');
                return;
            }
            
            // 显示筛选选项卡片
            document.getElementById('filter-options').style.display = 'block';
            
            // 隐藏其他卡片
            document.getElementById('viz-options').style.display = 'none';
            document.getElementById('results-card').style.display = 'none';
            
            // 填充筛选列下拉框
            const filterColumnSelect = document.getElementById('filter-column');
            filterColumnSelect.innerHTML = '';
            fileColumns.forEach(column => {
                filterColumnSelect.innerHTML += `<option value="${column}">${column}</option>`;
            });
            
            // 显示第一个列的信息
            if (fileColumns.length > 0) {
                showColumnInfo(fileColumns[0]);
            }
        });
        
        // 添加筛选条件按钮点击
        document.getElementById('add-filter-condition').addEventListener('click', function() {
            // 显示筛选条件模态框
            const filterModal = new bootstrap.Modal(document.getElementById('filter-modal'));
            filterModal.show();
        });
        
        // 监听操作符变化，显示或隐藏第二个值输入框
        document.getElementById('filter-operator').addEventListener('change', function() {
            const operator = this.value;
            const value2Container = document.getElementById('filter-value2-container');
            
            if (operator === 'between') {
                value2Container.style.display = 'block';
            } else {
                value2Container.style.display = 'none';
            }
        });
        
        // 筛选条件处理增强
        document.getElementById('filter-column').addEventListener('change', async function() {
            const column = this.value;
            await showColumnInfo(column);
            
            // 根据列的数据类型调整值输入框类型
            try {
                const response = await fetch(`/module/file-info/${encodeURIComponent(currentFilePath)}`);
                const result = await response.json();
                
                if (response.ok) {
                    const dataType = result.dtypes[column];
                    const valueInput = document.getElementById('filter-value');
                    const value2Input = document.getElementById('filter-value2');
                    
                    // 根据数据类型调整输入框
                    if (dataType.includes('int') || dataType.includes('float')) {
                        valueInput.type = 'number';
                        valueInput.step = dataType.includes('float') ? '0.01' : '1';
                        value2Input.type = 'number';
                        value2Input.step = dataType.includes('float') ? '0.01' : '1';
                        
                        // 添加最小/最大值范围提示
                        if (result.describe && result.describe[column]) {
                            const min = result.describe[column].min;
                            const max = result.describe[column].max;
                            if (min !== undefined && max !== undefined) {
                                valueInput.placeholder = `数值 (范围: ${min.toFixed(2)} - ${max.toFixed(2)})`;
                                value2Input.placeholder = `数值 (范围: ${min.toFixed(2)} - ${max.toFixed(2)})`;
                            }
                        }
                    } else if (dataType.includes('datetime')) {
                        valueInput.type = 'datetime-local';
                        value2Input.type = 'datetime-local';
                    } else {
                        valueInput.type = 'text';
                        value2Input.type = 'text';
                        valueInput.placeholder = '输入筛选值';
                        value2Input.placeholder = '输入上限值';
                    }
                }
            } catch (error) {
                console.error('获取列信息错误:', error);
            }
        });
        
        // 筛选操作符变化时的处理增强
        document.getElementById('filter-operator').addEventListener('change', function() {
            const operator = this.value;
            const value2Container = document.getElementById('filter-value2-container');
            const filterColumn = document.getElementById('filter-column').value;
            const valueInput = document.getElementById('filter-value');
            
            // 根据操作符调整输入提示
            switch(operator) {
                case 'eq':
                    valueInput.placeholder = '等于的值';
                    break;
                case 'gt':
                    valueInput.placeholder = '大于的值';
                    break;
                case 'lt':
                    valueInput.placeholder = '小于的值';
                    break;
                case 'ge':
                    valueInput.placeholder = '大于等于的值';
                    break;
                case 'le':
                    valueInput.placeholder = '小于等于的值';
                    break;
                case 'contains':
                    valueInput.placeholder = '包含的文本';
                    valueInput.type = 'text'; // 确保为文本输入
                    break;
            }
            
            if (operator === 'between') {
                value2Container.style.display = 'block';
            } else {
                value2Container.style.display = 'none';
            }
        });
        
        // 显示列信息函数
        async function showColumnInfo(column) {
            try {
                const response = await fetch(`/module/file-info/${encodeURIComponent(currentFilePath)}`);
                const result = await response.json();
                
                if (response.ok) {
                    const columnInfo = document.getElementById('filter-column-info');
                    columnInfo.innerHTML = '';
                    
                    // 获取列的数据类型
                    const dataType = result.dtypes[column];
                    const isNumeric = dataType.includes('int') || dataType.includes('float');
                    
                    // 创建信息HTML
                    let infoHTML = `<div class="alert alert-light p-2 mb-2">列: <strong>${column}</strong> (${dataType})</div>`;
                    
                    // 添加列的基本信息
                    if (isNumeric && result.describe && result.describe[column]) {
                        const desc = result.describe[column];
                        infoHTML += `<small>
                            <ul class="list-unstyled">
                                <li>最小值: ${desc.min?.toFixed(2) || 'N/A'}</li>
                                <li>最大值: ${desc.max?.toFixed(2) || 'N/A'}</li>
                                <li>平均值: ${desc.mean?.toFixed(2) || 'N/A'}</li>
                                <li>标准差: ${desc.std?.toFixed(2) || 'N/A'}</li>
                            </ul>
                        </small>`;
                    }
                    
                    columnInfo.innerHTML = infoHTML;
                }
            } catch (error) {
                console.error('获取列信息错误:', error);
            }
        }
        
        // 确认添加筛选条件
        document.getElementById('confirm-add-filter').addEventListener('click', function() {
            const column = document.getElementById('filter-column').value;
            const operator = document.getElementById('filter-operator').value;
            const value = document.getElementById('filter-value').value;
            
            // 验证输入
            if (!column || !operator || !value) {
                alert('请填写所有必填字段');
                return;
            }
            
            // 创建筛选条件对象
            const filterCondition = {
                column: column,
                operator: operator,
                value: value
            };
            
            // 如果是between操作符，需要第二个值
            if (operator === 'between') {
                const value2 = document.getElementById('filter-value2').value;
                if (!value2) {
                    alert('请填写上限值');
                    return;
                }
                filterCondition.value2 = value2;
            }
            
            // 添加到筛选条件列表
            filterConditions.push(filterCondition);
            
            // 关闭模态框
            bootstrap.Modal.getInstance(document.getElementById('filter-modal')).hide();
            
            // 更新筛选条件列表显示
            updateFilterConditionsList();
            
            // 清空表单值
            document.getElementById('filter-value').value = '';
            document.getElementById('filter-value2').value = '';
            
            // 显示应用和清除筛选按钮
            document.getElementById('apply-filters').style.display = 'inline-block';
            document.getElementById('clear-filters').style.display = 'inline-block';
        });
        
        // 更新筛选条件列表显示
        function updateFilterConditionsList() {
            const conditionsList = document.getElementById('filter-conditions-list');
            
            if (filterConditions.length === 0) {
                conditionsList.innerHTML = '<div class="alert alert-info">尚未添加筛选条件</div>';
                return;
            }
            
            let html = '<ul class="list-group">';
            
            filterConditions.forEach((condition, index) => {
                // 格式化操作符显示
                let opDisplay = '';
                switch(condition.operator) {
                    case 'eq': opDisplay = '等于'; break;
                    case 'gt': opDisplay = '大于'; break;
                    case 'lt': opDisplay = '小于'; break;
                    case 'ge': opDisplay = '大于等于'; break;
                    case 'le': opDisplay = '小于等于'; break;
                    case 'contains': opDisplay = '包含'; break;
                    case 'between': opDisplay = '介于'; break;
                    default: opDisplay = condition.operator;
                }
                
                // 格式化值显示
                let valueDisplay = condition.value;
                if (condition.operator === 'between' && condition.value2) {
                    valueDisplay = `${condition.value} 和 ${condition.value2} 之间`;
                }
                
                html += `
                <li class="list-group-item d-flex justify-content-between align-items-center">
                    <span>${condition.column} ${opDisplay} ${valueDisplay}</span>
                    <button class="btn btn-sm btn-danger remove-filter" data-index="${index}">删除</button>
                </li>`;
            });
            
            html += '</ul>';
            conditionsList.innerHTML = html;
            
            // 添加删除筛选条件的事件处理器
            document.querySelectorAll('.remove-filter').forEach(button => {
                button.addEventListener('click', function() {
                    const index = parseInt(this.getAttribute('data-index'));
                    filterConditions.splice(index, 1);
                    updateFilterConditionsList();
                    
                    if (filterConditions.length === 0) {
                        document.getElementById('apply-filters').style.display = 'none';
                        document.getElementById('clear-filters').style.display = 'none';
                        document.getElementById('save-filtered-data').style.display = 'none';
                        document.getElementById('export-filtered-data').style.display = 'none'; // 隐藏导出按钮
                    }
                });
            });
        }
        
        // 清除全部筛选条件
        document.getElementById('clear-filters').addEventListener('click', function() {
            filterConditions = [];
            updateFilterConditionsList();
            
            // 隐藏筛选相关按钮
            document.getElementById('apply-filters').style.display = 'none';
            document.getElementById('clear-filters').style.display = 'none';
            document.getElementById('save-filtered-data').style.display = 'none';
            document.getElementById('export-filtered-data').style.display = 'none'; // 隐藏导出按钮
            
            // 隐藏筛选结果
            document.getElementById('filter-results').style.display = 'none';
        });
        
        // 应用筛选 - 增强错误处理
        document.getElementById('apply-filters').addEventListener('click', async function() {
            if (filterConditions.length === 0) {
                alert('请添加至少一个筛选条件');
                return;
            }
            
            try {
                // 显示加载信息
                document.getElementById('filter-results').style.display = 'block';
                document.getElementById('filter-results-content').innerHTML = 
                    '<div class="alert alert-info">正在应用筛选条件，请稍候...</div>';
                
                // 发送筛选请求
                const response = await fetch('/module/filter-data', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        file_path: currentFilePath,
                        conditions: filterConditions
                    })
                });
                
                let result;
                try {
                    result = await response.json();
                } catch (e) {
                    const errorText = await response.text();
                    throw new Error(errorText || '无效的响应格式');
                }
                
                if (response.ok) {
                    // 显示筛选结果摘要
                    let resultHtml = `
                    <div class="alert alert-success">
                        筛选完成: 从 ${result.original_rows} 行数据中筛选出 ${result.filtered_rows} 行数据
                    </div>`;
                    
                    // 显示样本数据
                    if (result.filtered_rows > 0) {
                        resultHtml += '<h6>筛选结果样本数据:</h6>';
                        resultHtml += '<div class="table-responsive"><table class="table table-striped table-sm">';
                        
                        // 表头
                        resultHtml += '<thead><tr>';
                        result.columns.forEach(col => {
                            resultHtml += `<th>${col}</th>`;
                        });
                        resultHtml += '</tr></thead><tbody>';
                        
                        // 表格数据
                        result.sample_data.forEach(row => {
                            resultHtml += '<tr>';
                            result.columns.forEach(col => {
                                resultHtml += `<td>${row[col] !== null ? row[col] : 'N/A'}</td>`;
                            });
                            resultHtml += '</tr>';
                        });
                        
                        resultHtml += '</tbody></table></div>';
                        
                        // 显示按钮组
                        resultHtml += `
                        <div class="btn-group mt-3" role="group">
                            <button type="button" class="btn btn-success" id="save-filtered-data">保存筛选结果</button>
                            <button type="button" class="btn btn-primary ms-2" id="visualize-filtered-data">基于筛选结果可视化</button>
                        </div>`;
                    } else {
                        resultHtml += '<div class="alert alert-warning">没有符合筛选条件的数据</div>';
                    }
                    
                    document.getElementById('filter-results-content').innerHTML = resultHtml;
                    
                    // 添加基于筛选结果可视化的事件处理器
                    if (result.filtered_rows > 0) {
                        document.getElementById('visualize-filtered-data').addEventListener('click', function() {
                            // 显示可视化选项
                            document.getElementById('viz-options').style.display = 'block';
                            document.getElementById('viz-options').scrollIntoView({ behavior: 'smooth' });
                            
                            // 将当前的筛选条件保存到全局变量，供可视化使用
                            window.currentFilterConditions = [...filterConditions];
                            
                            // 显示提示信息
                            const alertDiv = document.createElement('div');
                            alertDiv.className = 'alert alert-info mb-3';
                            alertDiv.id = 'filtered-viz-alert';
                            alertDiv.innerHTML = '当前设置将基于<strong>筛选后的数据</strong>生成可视化图表';
                            
                            // 如果已经有提示则替换，否则添加
                            const existingAlert = document.getElementById('filtered-viz-alert');
                            if (existingAlert) {
                                existingAlert.replaceWith(alertDiv);
                            } else {
                                document.getElementById('viz-form').prepend(alertDiv);
                            }
                        });
                        
                        // 保存筛选数据按钮改为局部绑定事件
                        document.getElementById('save-filtered-data').addEventListener('click', saveFilteredData);
                        
                        // 显示导出按钮
                        document.getElementById('export-filtered-data').style.display = 'inline-block';
                        
                        // 导出筛选数据按钮改为局部绑定事件
                        document.getElementById('export-filtered-data').addEventListener('click', exportFilteredData);
                    }
                } else {
                    let errorMessage = result.detail || '未知错误';
                    document.getElementById('filter-results-content').innerHTML = `
                    <div class="alert alert-danger">
                        <h5>筛选失败</h5>
                        <p>${errorMessage}</p>
                        <div class="mt-3">
                            <h6>可能的原因:</h6>
                            <ul>
                                <li>筛选值类型与列的数据类型不匹配</li>
                                <li>数值列需要输入数字，而不是文本</li>
                                <li>日期列需要使用正确的日期格式</li>
                                <li>筛选条件可能导致空结果集</li>
                            </ul>
                        </div>
                    </div>`;
                }
            } catch (error) {
                console.error('应用筛选错误:', error);
                document.getElementById('filter-results-content').innerHTML = 
                    `<div class="alert alert-danger">筛选出错: ${error.message}</div>`;
            }
        });
        
        // 保存筛选结果
        async function saveFilteredData() {
            if (filterConditions.length === 0) {
                alert('请添加至少一个筛选条件');
                return;
            }
            
            // 创建导出格式选择对话框
            const formatDialogHtml = `
            <div class="modal fade" id="export-format-modal" tabindex="-1" aria-labelledby="export-format-label" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="export-format-label">选择导出格式</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="export-format-form">
                                <div class="mb-3">
                                    <label class="form-label">文件格式</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="export-format" id="format-xlsx" value="xlsx" checked>
                                        <label class="form-check-label" for="format-xlsx">
                                            Excel 文件 (.xlsx)
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="export-format" id="format-xls" value="xls">
                                        <label class="form-check-label" for="format-xls">
                                            Excel 97-2003 文件 (.xls)
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="export-format" id="format-csv" value="csv">
                                        <label class="form-check-label" for="format-csv">
                                            CSV 文件 (.csv)
                                        </label>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" id="confirm-export">导出</button>
                        </div>
                    </div>
                </div>
            </div>
            `;
            
            // 如果对话框不存在，则添加到文档中
            if (!document.getElementById('export-format-modal')) {
                document.body.insertAdjacentHTML('beforeend', formatDialogHtml);
            }
            
            // 显示对话框
            const formatModal = new bootstrap.Modal(document.getElementById('export-format-modal'));
            formatModal.show();
            
            // 确认导出按钮点击事件
            document.getElementById('confirm-export').addEventListener('click', async function() {
                // 获取选择的格式
                const exportFormat = document.querySelector('input[name="export-format"]:checked').value;
                
                // 关闭对话框
                formatModal.hide();
                
                try {
                    // 显示加载信息
                    document.getElementById('filter-results-content').innerHTML += 
                        '<div class="alert alert-info" id="save-status">正在保存筛选结果，请稍候...</div>';
                    
                    // 发送保存筛选结果请求
                    const response = await fetch(`/module/save-filtered-data?export_format=${exportFormat}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            file_path: currentFilePath,
                            conditions: filterConditions
                        })
                    });
                    
                    let result;
                    try {
                        result = await response.json();
                    } catch (e) {
                        const errorText = await response.text();
                        throw new Error(errorText || '无效的响应格式');
                    }
                    
                    if (response.ok) {
                        // 更新全局变量，使用新的筛选后文件
                        filteredFilePath = result.filtered_file;
                        
                        // 显示保存成功信息和下载链接
                        document.getElementById('save-status').outerHTML = `
                        <div class="alert alert-success">
                            筛选数据保存成功，共 ${result.rows} 行数据
                            <div class="mt-2">
                                <a href="${result.download_url}" class="btn btn-sm btn-success" download>
                                    <i class="bi bi-download"></i> 下载${exportFormat.toUpperCase()}文件
                                </a>
                                <button type="button" class="btn btn-sm btn-primary ms-2" id="use-filtered-file">
                                    使用筛选结果进行可视化
                                </button>
                            </div>
                        </div>`;
                        
                        // 添加使用筛选后文件的事件处理器
                        document.getElementById('use-filtered-file').addEventListener('click', function() {
                            currentFilePath = filteredFilePath;
                            fileColumns = result.columns;
                            
                            alert('已切换到筛选后的数据文件，现在可以使用筛选后的数据进行可视化');
                            
                            // 显示创建可视化的选项
                            document.getElementById('create-viz').click();
                        });
                    } else {
                        document.getElementById('save-status').outerHTML = 
                            `<div class="alert alert-danger">保存失败: ${result.detail || '未知错误'}</div>`;
                    }
                } catch (error) {
                    console.error('保存筛选结果错误:', error);
                    document.getElementById('save-status').outerHTML = 
                        `<div class="alert alert-danger">保存出错: ${error.message}</div>`;
                }
            }, { once: true }); // 使用once选项确保事件只触发一次
        }

        // 导出筛选结果
        async function exportFilteredData() {
            if (filterConditions.length === 0) {
                alert('请添加至少一个筛选条件');
                return;
            }

            // 创建导出格式选择对话框
            const formatDialogHtml = `
            <div class="modal fade" id="export-format-modal" tabindex="-1" aria-labelledby="export-format-label" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="export-format-label">选择导出格式</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="export-format-form">
                                <div class="mb-3">
                                    <label class="form-label">文件格式</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="export-format" id="format-xlsx" value="xlsx" checked>
                                        <label class="form-check-label" for="format-xlsx">
                                            Excel 文件 (.xlsx)
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="export-format" id="format-xls" value="xls">
                                        <label class="form-check-label" for="format-xls">
                                            Excel 97-2003 文件 (.xls)
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="export-format" id="format-csv" value="csv">
                                        <label class="form-check-label" for="format-csv">
                                            CSV 文件 (.csv)
                                        </label>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" id="confirm-export">导出</button>
                        </div>
                    </div>
                </div>
            </div>
            `;
            
            // 如果对话框不存在，则添加到文档中
            if (!document.getElementById('export-format-modal')) {
                document.body.insertAdjacentHTML('beforeend', formatDialogHtml);
            }
            
            // 显示对话框
            const formatModal = new bootstrap.Modal(document.getElementById('export-format-modal'));
            formatModal.show();
            
            // 确认导出按钮点击事件
            document.getElementById('confirm-export').addEventListener('click', async function() {
                // 获取选择的格式
                const exportFormat = document.querySelector('input[name="export-format"]:checked').value;
                
                // 关闭对话框
                formatModal.hide();
                
                try {
                    // 显示加载信息
                    document.getElementById('filter-results-content').innerHTML += 
                        '<div class="alert alert-info" id="export-status">正在导出筛选结果，请稍候...</div>';
                    
                    // 发送导出筛选结果请求
                    const response = await fetch(`/module/export-filtered-data?export_format=${exportFormat}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            file_path: currentFilePath,
                            conditions: filterConditions
                        })
                    });
                    
                    let result;
                    try {
                        result = await response.json();
                    } catch (e) {
                        const errorText = await response.text();
                        throw new Error(errorText || '无效的响应格式');
                    }
                    
                    if (response.ok) {
                        // 显示导出成功信息和下载链接
                        document.getElementById('export-status').outerHTML = `
                        <div class="alert alert-success">
                            筛选数据导出成功，共 ${result.rows} 行数据
                            <div class="mt-2">
                                <a href="${result.download_url}" class="btn btn-sm btn-success" download>
                                    <i class="bi bi-download"></i> 下载${exportFormat.toUpperCase()}文件
                                </a>
                            </div>
                        </div>`;
                    } else {
                        document.getElementById('export-status').outerHTML = 
                            `<div class="alert alert-danger">导出失败: ${result.detail || '未知错误'}</div>`;
                    }
                } catch (error) {
                    console.error('导出筛选结果错误:', error);
                    document.getElementById('export-status').outerHTML = 
                        `<div class="alert alert-danger">导出出错: ${error.message}</div>`;
                }
            }, { once: true }); // 使用once选项确保事件只触发一次
        }
    </script>
</body>
</html> 